class Camera {
  runing = false;
  options = {
    video: this.createNode({
      tag: "video",
      attr: { muted: "", autoplay: "", playsinline: "" },
    }),
    canvas: this.createNode({
      tag: "canvas",
    }),
  };

  constructor(options = {}) {
    this.options = Object.assign(this.options, options);
  }

  on(type, callback) {
    const { video } = this.options;
    if (type === "open") {
      video.addEventListener("play", (e) => {
        this.runing = true;
        callback(e);
      });
    }
    if (type === "close") {
      video.addEventListener("pause", (e) => {
        this.runing = false;
        callback(e);
      });
    }
  }

  open(options= {}) {
    if (this.runing === true) return;
    const { video } = this.options;
    const { facingMode = "user" } = options;
    navigator.mediaDevices
      .getUserMedia({ video: { facingMode } })
      .then((stream) => {
        video.srcObject = stream;
      })
      .catch(() => {
        this.runing = false;
        console.log("未获取摄像头权限");
      });
  }

  close() {
    if (this.runing === false) return;
    const { video } = this.options;
    video.pause();
    video.srcObject.getTracks().forEach((track) => track.stop());
  }

  createNode(options) {
    const { tag, attr, style } = options;
    const el = document.createElement(tag);
    for (const key in attr) el.setAttribute(key, attr[key]);
    for (const key in style) el.style.setProperty(key, style[key]);
    return el;
  }

  captureImage(clear = false) {
    const { video, canvas } = this.options;
    const width = video.videoWidth;
    const height = video.videoHeight;
    const dpr = window.devicePixelRatio || 1;
    canvas.width = width * dpr;
    canvas.height = height * dpr;
    const ctx = canvas.getContext("2d");
    ctx.scale(dpr, dpr);
    if (clear) {
      ctx.clearRect(video, 0, 0, width, height);
    } else {
      ctx.drawImage(video, 0, 0, width, height);
    }
    return canvas.toDataURL("image/jpeg", 0.5);
  }
}
